//
//  NSDate+Extension.m
//  Health
//
//  Created by LeeJay on 16/8/24.
//  Copyright © 2016年 LeeJay. All rights reserved.
//

#import "NSDate+Extension.h"

@implementation NSDate (Extension)

+ (NSDate *)dateFromString:(NSString *)dateString
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    if (!(dateString.length > 0)) {
        dateString = @"2016-01-01 00:00:00";
    }
    return [dateFormatter dateFromString:dateString];
}

+ (NSString *)stringFromDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    if (!date) {
        date = [NSDate date];
    }
    return [dateFormatter stringFromDate:date];
}

+ (NSDate *)getTodayAgoWithDays:(NSInteger)days
{
    NSDate *endDate = [NSDate date];
    NSString *dateStr = [[self stringFromDate:endDate] substringToIndex:10];
    NSDate *newEndDate = [self dateFromString:[dateStr stringByAppendingString:@" 00:00:00"]];
    
    NSTimeInterval timeInterval= [newEndDate timeIntervalSinceReferenceDate];
    timeInterval -= days * 3600 * 24;
    return [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
}

@end
